package com.wsm.common.config;

import com.wsm.common.domain.ConfigDO;
import com.wsm.common.mapper.ConfigMapper;
import com.wsm.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name: config
 * @Author: wangshimin
 * @Date: 2020/2/14  18:42
 * @Description: 系统配置
 */
@Slf4j
@Component
public class BaseConfig {
    @Autowired
    ConfigMapper configMapper;

    private static Map<String, Object> configMap;

    public Object getMap(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        if (null == configMap) {
            configMap = new HashMap<>();
            findMap(key);
        }
        if (!(configMap.containsKey(key))) {
            findMap(key);
        }
        Object value = configMap.get(key);
        if (null != value) {
            return value;
        }
        return null;
    }

    private synchronized void findMap(String key) {
        if (configMap.containsKey(key)) {
            return;
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("sysKey", key);
        List<ConfigDO> list = configMapper.list(map);
        if (null != list && list.size() > 0) {
            ConfigDO configDO = list.get(0);
            if (null != configDO) {
                configMap.put(key, configDO.getSysValue());
                return;
            }
        }
        configMap.put(key, null);
    }

    public synchronized void setMap(String key, String value) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        if (null == configMap) {
            configMap = new HashMap<>();
        }
        configMap.put(key, value);
    }

    public synchronized void deleteKey(String key) {
        if (StringUtils.isEmpty(key) || null == configMap) {
            return;
        }
        if (configMap.containsKey(key)) {
            configMap.put(key, null);
        }
    }
}
